import axios from 'axios'
import Vue from 'vue'

import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		todos: [],
		type: 'all',
	},
	mutations: {
		// 获取todos数据
		getTodos(state, data) {
			state.todos = data.reverse()
		},
		// 添加数据
		addTodos(state, data) {
			state.todos.unshift(data)
		},
		// 删除数据
		delTodos(state, id) {
			state.todos = state.todos.filter(item => item.id !== id)
		},
		// 改变状态
		changeIsDone(state, data) {
			state.todos.find(item => item.id === data.id).isDone = data.isDone
		},
		// 改变类型
		changeType(state, type) {
			state.type = type
		},
	},
	actions: {
		async GETTODOS(context) {
			const res = await axios.get('http://localhost:3000/todos')
			context.commit('getTodos', res.data)
		},
		async ADDTODOS(context, data) {
			await axios({
				method: 'post',
				url: 'http://localhost:3000/todos',
				data,
			})
			context.commit('addTodos', data)
		},
		async DELTODOS(context, id) {
			await axios({
				method: 'delete',
				url: 'http://localhost:3000/todos/' + id,
			})
			context.commit('delTodos', id)
		},
		async CHANGEISDONE(context, data) {
			await axios({
				method: 'patch',
				url: 'http://localhost:3000/todos/' + data.id,
				data,
			})
			context.commit('changeIsDone', data)
		},
	},
	getters: {
		// 展示不同列表
		showList(state) {
			switch (state.type) {
				case 'active':
					return state.todos.filter(item => !item.isDone)
				case 'completed':
					return state.todos.filter(item => item.isDone)
				default:
					return state.todos
			}
		},
	},
})
export default store
